//
//  UserAccount.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/12.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit




class UserAccount: NSObject , NSCoding{
    
    //定义的属性
    var access_token : String
    var expires_in : NSTimeInterval
    var expires_date : NSDate
    var uid : String
    //友好显示名称
    var name : String?
    //用户头像地址（大图），180×180像素
    var avatar_large : String?
    
    //字典转模型
    init(dict : [String:AnyObject?]) {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        expires_date = NSDate(timeIntervalSinceNow: expires_in) as NSDate
        uid = dict["uid"] as! String
    }
    
    //归档存储地址
    static let pathString = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as! String).stringByAppendingPathComponent("account.plist")
    
    
   //提供获得accounttoken的方法
    class func loadAccountToken(para:[String:String], finished:(account:UserAccount?)->())
    {
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        HJCNetWorkTools.requestJSON(.POST, URLString: urlStr, parameters:para) { (JSON) -> () in
            //如果出现错误，直接返回
            if JSON == nil
            {
                //错误回调
                finished(account: nil)
                return
            }
            
            //字典装模型
            // JSON 有可能是字典也有可能是数组
            let account = UserAccount(dict: JSON as! [String : AnyObject])
            
            //从服务器获取用户信息
            account.loadUserInfo(finished)
        }
    }
    
   //https://api.weibo.com/2/users/show.json
    func loadUserInfo(finished:(account:UserAccount?)->())
    {
        //请求用户信息
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let param = ["uid":uid, "access_token":access_token]
        
        HJCNetWorkTools.requestJSON(.GET, URLString: urlStr, parameters: param) { (JSON)  in
            //如果出现错误，直接返回
            if JSON == nil
            {
                //错误回调
                finished(account: nil)
                return
            }
            
            let dict = JSON as! [String : AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            //归档保存
            NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.pathString)
            
            //            println(self.name)
            
            //完成后回调
            finished(account: self)
        }
        
    }
    
    
    //从沙盒读取数据
    class func loadAccountFromSandBox() -> UserAccount?
    {
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.pathString) as? UserAccount
        {
            if account.expires_date.compare(NSDate()) == NSComparisonResult.OrderedDescending
            {
                return account
            }
        }
       return nil
    }
    
    
    
    //MARK: - NSCoding
    func encodeWithCoder(aCoder: NSCoder)
    {
        //归档
        aCoder.encodeObject(access_token, forKey:"access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    required init(coder aDecoder: NSCoder)
    {
        //解档
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in") as NSTimeInterval
        uid = aDecoder.decodeObjectForKey("uid") as! String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as! NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}
